package com.xiaochun.jiankangapp.base

import android.app.ProgressDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewbinding.ViewBinding
import com.xiaochun.jiankangapp.R
import com.xiaochun.jiankangapp.extension.lazyGlobalViewModel
import com.xiaochun.jiankangapp.extension.onClick
import com.xiaochun.jiankangapp.model.Response
import com.xiaochun.jiankangapp.model.UploadResultModel
import com.xiaochun.jiankangapp.network.Request
import com.xiaochun.jiankangapp.viewmodel.LoginViewModel
import java.io.File

abstract class BaseActivity : AppCompatActivity() {
    protected val loginViewModel: LoginViewModel by lazyGlobalViewModel()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        enableEdgeToEdge()
//        ViewCompat.setOnApplyWindowInsetsListener(window.decorView) { v, insets ->
//            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
//            insets
//        }
    }

    suspend fun upload(file: File): Response<UploadResultModel> {
        return Request.postWithFile<UploadResultModel>(
            "api/common/upload",
            mapOf("file" to file)
        )
    }

    private var loading: ProgressDialog? = null

    fun showLoading() {
        val l = loading ?: ProgressDialog(this).also {
            it.setCancelable(false)
            it.setCanceledOnTouchOutside(false)
            loading = it
        }
        l.show()
    }

    fun hideLoading() {
        val l = loading ?: return
        l.dismiss()
    }

    fun <T : ViewBinding> createVB(clz: Class<T>): T {
        val method = clz.getMethod(
            "inflate",
            LayoutInflater::class.java,
            ViewGroup::class.java,
            Boolean::class.java
        )
        return method.invoke(
            null,
            layoutInflater,
            window.findViewById<ViewGroup>(android.R.id.content),
            false
        ) as T
    }

    override fun onContentChanged() {
        super.onContentChanged()
        findViewById<View>(R.id.back)?.onClick {
            onBackPressed()
        }
    }

    inline fun <reified T : ViewBinding> setContentView(): T {
        val vb = createVB(T::class.java)
        setContentView(vb.root)
        return vb
    }
}